﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<!-- 员工基本信息 - 优先级最高 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>员工基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '姓名为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_StaffNo_FormItem"
								prop="Entity.StaffNo"
								:rules="[{ required: true, message: '工号为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Gender_FormItem" prop="Entity.Gender" :rules="[{ required: true, message: '性别为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="性别" tooltip="员工性别" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.Gender" clearable class="width100">
									<el-option v-for="item in GENDER_OPTIONS" :key="item" :value="item" :label="item"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Phone_FormItem" prop="Entity.Phone" :rules="[{ required: true, message: '手机号为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="手机号" tooltip="手机号码" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Phone" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<!-- 身份证号 -->
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_IdCardNo_FormItem"
								prop="Entity.IdCardNo"
								:rules="[{ required: true, message: '身份证号为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="身份证号" tooltip="身份证号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.IdCardNo" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<!-- 出生日期 -->
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_BirthDate_FormItem"
								prop="Entity.BirthDate"
								:rules="[{ required: true, message: '出生日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="出生日期" tooltip="出生日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.BirthDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<!-- 所属部门 -->
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model:model-value="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" />
						</el-col>
						<!-- 公司 -->
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" prop="Entity.OrgId" :disabled="true" />
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Email_FormItem" prop="Entity.Email">
								<template #label>
									<WtmLabelTooltip label="邮箱" tooltip="电子邮箱" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Email" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 转正基本信息 - 第二优先级 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>转正基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_EntryDate_FormItem" prop="Entity.EntryDate">
								<template #label>
									<WtmLabelTooltip label="入职日期" tooltip="入职日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.EntryDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_RegDate_FormItem" prop="Entity.RegDate">
								<template #label>
									<WtmLabelTooltip label="转正日期" tooltip="转正日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.RegDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 试用期信息 - 第三优先级 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>试用期信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ProbationStartDate_FormItem" prop="Entity.ProbationStartDate">
								<template #label>
									<WtmLabelTooltip label="试用期起始日期" tooltip="试用期起始日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.ProbationStartDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ProbationEndDate_FormItem" prop="Entity.ProbationEndDate">
								<template #label>
									<WtmLabelTooltip label="试用期结束日期" tooltip="试用期结束日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.ProbationEndDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<!-- <el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ProbationSalary_FormItem" prop="Entity.ProbationSalary">
								<template #label>
									<WtmLabelTooltip label="试用期薪资" tooltip="试用期薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.ProbationSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col> -->
					</el-row>
				</div>

				<!-- 转正薪资信息 - 第四优先级 -->
				<!-- <div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>转正薪资信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_RegularSalary_FormItem" prop="Entity.RegularSalary">
								<template #label>
									<WtmLabelTooltip label="转正后薪资" tooltip="转正后薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.RegularSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div> -->

				<!-- 转正评估内容 - 第五优先级 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>转正评估内容</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_JobContent_FormItem"
								prop="Entity.JobContent"
								:rules="[{ required: true, message: '试用期工作内容为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="试用期工作内容" tooltip="试用期主要工作内容描述" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.JobContent" type="textarea" :rows="3" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_JobAchievements_FormItem"
								prop="Entity.JobAchievements"
								:rules="[{ required: true, message: '试用期工作成果为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="试用期工作成果" tooltip="试用期取得的主要工作成果" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.JobAchievements" type="textarea" :rows="3" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_RegOpinion_FormItem" prop="Entity.RegOpinion">
								<template #label>
									<WtmLabelTooltip label="转正意见" tooltip="转正申请意见" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.RegOpinion" type="textarea" :rows="3" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_Remarks_FormItem" prop="Entity.Remarks">
								<template #label>
									<WtmLabelTooltip label="其他说明" tooltip="其他需要说明的事项" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remarks" type="textarea" :rows="3" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 单据信息 - 最后展示 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<el-row :gutter="20"></el-row>
			</el-form>
		</el-card>

		<!-- <el-tab-pane label="学习经历" name="personeducations" v-if="stateData.vmModel.Entity.ID">
				<SysPersonEducation :search-bar="false" :toolbar="true" :is-disabled="true" :person-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane>

			<el-tab-pane label="家庭成员" name="personfamilies" v-if="stateData.vmModel.Entity.ID">
				<SysPersonFamily :search-bar="false" :toolbar="true" :is-disabled="true" :person-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane>

			<el-tab-pane label="工作经历" name="personworks" v-if="stateData.vmModel.Entity.ID">
				<SysPersonWork :search-bar="false" :toolbar="true" :is-disabled="true" :person-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane>

			<el-tab-pane label="培训考试" name="persontrainexams" v-if="stateData.vmModel.Entity.ID">
				<SysPersonTrainExam :search-bar="false" :toolbar="true" :is-disabled="true" :person-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane>

			<el-tab-pane label="员工体检" name="personmedicals" v-if="stateData.vmModel.Entity.ID">
				<SysPersonMedical :search-bar="false" :toolbar="true" :is-disabled="true" :person-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane>

			<el-tab-pane label="员工履历" name="personresumes" v-if="stateData.vmModel.Entity.ID">
				<SysPersonResume :search-bar="false" :toolbar="true" :is-disabled="true" :person-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane>

			<el-tab-pane label="员工合同" name="personcontracts" v-if="stateData.vmModel.Entity.ID">
				<SysPersonContract :search-bar="false" :toolbar="true" :is-disabled="true" :person-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane> -->
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrProbationRequestBillApi as api } from '/@/views/hr/syshrprobationrequestbill/api';
import other from '/@/utils/other';
import { ISysHrProbationRequestBillVm } from '/@/views/hr/syshrprobationrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { commonApi } from '/@/api/common';

import SysPersonEducation from '/@/views/person/syspersoneducation/index.vue';
import SysPersonFamily from '/@/views/person/syspersonfamily/index.vue';
import SysPersonWork from '/@/views/person/syspersonwork/index.vue';
import SysPersonTrainExam from '/@/views/person/syspersontrainexam/index.vue';
import SysPersonMedical from '/@/views/person/syspersonmedical/index.vue';
import SysPersonResume from '/@/views/person/syspersonresume/index.vue';
import SysPersonContract from '/@/views/person/syspersoncontract/index.vue';

const GENDER_OPTIONS = ['男', '女', '其他'] as const;

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
	SUBMITTING: '提交中',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
	COMPLETED: '已完成',
	CANCELLED: '已取消',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);

const stateData = reactive<IViewModel<ISysHrProbationRequestBillVm>>({
	vmModel: {
		Entity: {
			EntryDate: null,
			RegDate: null,
			ProbationStartDate: null,
			ProbationEndDate: null,
			ProbationSalary: null,
			RegularSalary: null,
			JobContent: null,
			JobAchievements: null,
			Remarks: null,
			RegOpinion: null,
			Status: null,
			RecruitNo: null,
			ArrivalDate: null,
			CurrentSalary: null,
			ExpectedSalary: null,
			WorkExperience: null,
			InitialTestTime: null,
			InitialResult: null,
			InitialComment: null,
			ReExamTime: null,
			ReExamResult: null,
			ReExamComment: null,
			FinalResult: null,
			FinalRemark: null,
			RejectReason: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			Approver: null,
			ApprovalTime: null,
			Name: null,
			StaffNo: null,
			BirthDate: null,
			Age: null,
			Gender: null,
			Ethnicity: null,
			HighestEducation: null,
			MaritalStatus: null,
			PhotoId: null,
			IdCardNo: null,
			IdCardFrontPhotoId: null,
			IdCardBackPhotoId: null,
			HouseholdRegistration: null,
			NativePlace: null,
			PoliticalStatus: null,
			PartyJoinDate: null,
			PartyBranch: null,
			ArchiveLocation: null,
			ArchiveNo: null,
			ArchiveTransferOutDate: null,
			ArchiveTransferInDate: null,
			HomeAddress: null,
			Phone: null,
			Email: null,
			SalaryBank: null,
			SalaryAccount: null,
			BonusBank: null,
			BonusAccount: null,
			OrgId: null,
			GroupId: null,
			JobPositionId: null,
			ResumeId: null,
			HireDate: null,
			ConfirmationDate: null,
			EmploymentType: null,
			ContractType: null,
			ContractNo: null,
			ContractStartDate: null,
			ContractEndDate: null,
			ResignationDate: null,
			ResignationReason: null,
			ResignationType: null,
			State: null,
			BloodType: null,
			Hobbies: null,
		},
		ActionName: null,
		IsMyApprove: false,
		Remark: null,
	},

	AllSysOrgs: [] as any[],
	AllSysGroups: [] as any[],
	AllSysJobPositions: [] as any[],
});

// 计算属性
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

// 统一的成功处理函数
const handleSuccess = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
	}

	emit('refresh');

	// 统一处理ID设置
	if (response?.Entity?.ID) {
		stateData.vmModel.Entity = response.Entity;
	} else if (response?.ID) {
		stateData.vmModel.Entity.ID = response.ID;
	}

	// 根据操作类型处理不同逻辑
	if (isSubmit) {
		closeDialog();
	} else {
		hasSavedOnce.value = true;
	}

	loading.value = false; // 重置loading状态

	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	other.validateFormWithMessage(formRef.value, () => {
		loading.value = true;
		beforeSubmit();
		apiCall()
			.then((response: any) => handleSuccess(response, isSubmit))
			.catch(handleError);
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		true
	);
};

// 提交
const onSubmit = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true
	);
};

const activeTab = ref('main');

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 获取当前登录人信息
const getCurrentPersonInfo = async () => {
	try {
		const response = await commonApi().getPersonInfo({});
		if (response && response.Data) {
			const personInfo = response.Data;
			// 自动填充当前登录人的信息
			stateData.vmModel.Entity.Name = personInfo.Name || '';
			stateData.vmModel.Entity.StaffNo = personInfo.StaffNo || '';
			stateData.vmModel.Entity.Gender = personInfo.Gender || '';
			stateData.vmModel.Entity.Phone = personInfo.Phone || '';
			stateData.vmModel.Entity.Email = personInfo.Email || '';
			stateData.vmModel.Entity.GroupId = personInfo.GroupId || null;
			stateData.vmModel.Entity.IdCardNo = personInfo.IdCardNo || '';
			stateData.vmModel.Entity.BirthDate = personInfo.BirthDate || null;
			stateData.vmModel.Entity.OrgId = personInfo.OrgId || null;
			stateData.vmModel.Entity.EntryDate = personInfo.HireDate || null;
		}
	} catch (error) {
		console.warn('获取当前登录人信息失败:', error);
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [billCode] = await Promise.allSettled([api().getBillCode(), getCurrentPersonInfo()]);

	// 处理结果

	if (billCode.status === 'fulfilled') {
		stateData.vmModel.Entity.BillCode = billCode.value.Data as string;
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: hasEntityId.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
